package cn.itlaobing.eshop.web.servlet;

import cn.itlaobing.eshop.dao.UserDao;
import cn.itlaobing.eshop.entity.Users;
import cn.itlaobing.eshop.exception.BusinessExceeption;
import cn.itlaobing.eshop.service.UserService;
import cn.itlaobing.eshop.web.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/11/15.
 */
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    @RequestMapping("/login")
    public void doLogin(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException{

        req.setCharacterEncoding("utf-8");

        String useraccount=req.getParameter("username");

        String userpassword=req.getParameter("password");

        UserService userService=new UserService();


        try {
            Users us=userService.login(useraccount,userpassword);
            if (us!=null){
                req.setAttribute("USERS",us);
                resp.sendRedirect(req.getContextPath()+"/home/show");
                return;
            }else{
                req.setAttribute("MSG","用户名或密码不能为空！");
                toView(req,resp,"/login");
                return;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    @RequestMapping("/register")
    public void doRegister(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{

        request.setCharacterEncoding("utf-8");
        String useraccount=request.getParameter("username");
        String password=request.getParameter("password");

        UserService userService=new UserService();
        Users users=new Users();
        users.setUserAccount(useraccount);
        users.setUserPassword(password);
        int r=0;
        try {
            r=userService.register(users);
        } catch (BusinessExceeption businessExceeption) {
            businessExceeption.printStackTrace();
        }

        toView(request,response,"/login");

    }
    @RequestMapping("/init")
    public void  login(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request,response);
    }
    @RequestMapping("/registerinit")
    public void  register(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        request.getRequestDispatcher("/WEB-INF/views/register.jsp").forward(request,response);
    }
}

